package num29;

/**
 * @author : DuJiabao
 * @Date : 2021/1/22 14:17
 * @Project : sword-finger-offer
 * @File : null.java
 * @Desc :输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */
public class Solution {
    /**
     * 矩阵，一层一层输出。最后有可能剩一行或一列，将它输出，就结束了。
     * @param matrix
     * @return
     */
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int left = 0;
        int up = 0;
        int right = matrix[0].length - 1;
        int down = matrix.length - 1;
        int[] res = new int[matrix[0].length * matrix.length];
        int start = 0;
        while (left < right && up < down) {
            for (int i = left; i < right; i++) {
                res[start++] = matrix[up][i];
            }
            for (int i = up; i < down; i++) {
                res[start++] = matrix[i][right];
            }
            for (int i = right; i > left; i--) {
                res[start++] = matrix[down][i];
            }
            for (int i = down; i > up; i--) {
                res[start++] = matrix[i][left];
            }
            left++;
            right--;
            up++;
            down--;
        }
        if (left == right) {
            for (int i = up; i <= down; i++) {
                res[start++] = matrix[i][left];
            }
            return res;
        }
        if (up == down) {
            for (int i = left; i <= right; i++) {
                res[start++] = matrix[up][i];
            }
            return res;
        }
        return res;
    }

}
